package com.fei.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.domain.Page;
import com.fei.yygh.hosp.repository.DepartmentRepository;
import com.fei.yygh.hosp.service.DepartmentService;
import com.fei.yygh.model.hosp.Department;
import com.fei.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    //上传科室接口
    @Override
    public void save(Map<String, Object> objectMap) {
        String objectMapStr = JSONObject.toJSONString(objectMap);
        //将Map集合转换为对象
        Department department = JSONObject.parseObject(objectMapStr, Department.class);

        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());
        //判断是否存在
        if(departmentExist != null) {
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        }else {
            department.setIsDeleted(0);
            department.setUpdateTime(new Date());
            department.setCreateTime(new Date());
            departmentRepository.save(department);
        }
    }

    //查询科室接口
    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {

        //创建pageable对象，设置当前页和每页记录数, 0 是第一页
        Pageable pageable = PageRequest.of(page-1, limit);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);


        //创建example对象
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);

        return all;
    }

    //删除科室信息
    @Override
    public void remove(String hospital, String depcode) {
        //根医院编号和科室编号查询信息
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hospital, depcode);
        if(department != null) {
            departmentRepository.deleteById(department.getId());
        }

    }
}
